package com.misc.tunewsreader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * Handles the subscribed newsgroups
 * 
 */
public class GroupManager {
	private SharedPreferences prefs;
	private List<String> favorites;
	private Context context;

	public GroupManager(Context context) {
		prefs = context.getSharedPreferences("favorites", 0);
		String[] fav = prefs.getString("favorite", "").split("::");
		favorites = new ArrayList<String>();

		for (int i = 0; i < fav.length; i++) {
			if (fav[i].length() > 1)
				favorites.add(fav[i]);
		}

		this.context = context;
	}

	/**
	 * Checks if the user has subscribed to the given newsgroup
	 * 
	 * @param groupname
	 *            the name of the newsgroups
	 * @return true if the user has subscribed to this group, false otherwise
	 */
	public boolean isFavorite(String groupname) {
		return favorites.contains(groupname);
	}

	/**
	 * Subscribe to/unsubscribe from a newsgroup
	 * 
	 * @param groupname
	 *            name of the newsgroup
	 * @param is_fav
	 *            true to subscribe, false to unsubscribe
	 */
	public void setFavorite(String groupname, boolean is_fav) {
		if (!is_fav)
			favorites.remove(groupname);
		else
			favorites.add(groupname);

		String new_fav = "";
		for (int i = 0; i < favorites.size(); i++) {
			new_fav += favorites.get(i) + "::";
		}

		Editor edit = prefs.edit();
		edit.putString("favorite", new_fav);
		edit.commit();
	}

	/**
	 * Get a list of all subscribed newsgroups
	 * 
	 * @return list of subscribed newsgroups
	 */
	public List<String> getFavoriteList() {
		return favorites;
	}

	public ArrayList<ListItem> generateListView(List<String> groups,
			List<NNTPGroup> group_list) {
		// get preferences
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		// split newsgroups into categories
		TreeMap<String, ArrayList<String>> cat = new TreeMap<String, ArrayList<String>>();
		for (int i = 0; i < groups.size(); i++) {
			String title, name;

			String group = groups.get(i);

			// full hierarchy, new group for every '.'
			if (prefs.getString("pref_group_hierarchy", "-1").equals("-1")) {
				if (group.lastIndexOf('.') != -1) {
					title = group.substring(0, group.lastIndexOf('.'));
					name = group.substring(group.lastIndexOf('.') + 1);
				} else {
					title = " ";
					name = group;
				}
			} else {
				// n-level-hierarchy
				int n = Integer.parseInt(prefs.getString(
						"pref_group_hierarchy", "-1"));
				int[] dot_pos = new int[n];

				title = " ";
				name = group;
				for (int j = 0; j < n; j++) {
					if (j == 0)
						dot_pos[j] = group.indexOf('.');
					else
						dot_pos[j] = group.indexOf('.', dot_pos[j - 1] + 1);

					if (dot_pos[j] == -1 && j == 0)
						break;

					if (dot_pos[j] == -1) {
						title = group.substring(0, dot_pos[j - 1]);
						name = group.substring(dot_pos[j - 1] + 1);
						break;
					} else {
						title = group.substring(0, dot_pos[j]);
						name = group.substring(dot_pos[j] + 1);
					}
				}
			}

			if (!cat.containsKey(title)) {
				ArrayList<String> names = new ArrayList<String>();
				names.add(name);
				cat.put(title, names);
			} else {
				cat.get(title).add(name);
			}
		}

		ArrayList<ListItem> items = new ArrayList<ListItem>();

		// check if users only want to see unread groups
		boolean only_unread = prefs.getBoolean("pref_only_unread", false);

		// add newsgroups to list
		Iterator<TreeMap.Entry<String, ArrayList<String>>> it = cat.entrySet()
				.iterator();
		while (it.hasNext()) {
			TreeMap.Entry<String, ArrayList<String>> pairs = (TreeMap.Entry<String, ArrayList<String>>) it
					.next();
			// if last item is section title, remove it
			if (items.size() > 0 && items.get(items.size() - 1).isSection())
				items.remove(items.size() - 1);
			// add section title
			items.add(new ListSection(pairs.getKey()));
			// sort newsgroups
			String[] names = new String[pairs.getValue().size()];
			pairs.getValue().toArray(names);
			Arrays.sort(names);
			for (int i = 0; i < names.length; i++) {
				String full_name = (pairs.getKey().equals(" ") ? names[i]
						: pairs.getKey() + "." + names[i]);
				// get number of unread posts
				int unread = 0;
				if (group_list != null) {
					Log.d("TUGNGFav", "Get number of unread posts");
					for (int n = 0; n < group_list.size(); n++) {
						if (group_list.get(n).getName().equals(full_name)) {
							unread = NNTPClient.getNewAndUnreadCount(full_name,
									group_list.get(n));
							break;
						}
					}
				} else {
					// unread = NNTPClient.getUnreadCount(full_name);
					unread = -1;
				}
				if ((only_unread && unread != 0) || !only_unread) {
					// unread = -1 => no data available
					if (unread == -1)
						unread = 0;
					items.add(new ListEntry(names[i], full_name, unread));
				}
			}
		}
		// if last item is section title, remove it
		if (items.size() > 0 && items.get(items.size() - 1).isSection())
			items.remove(items.size() - 1);
		return items;
	}

	public ArrayList<ListItem> generateListView(List<String> groups) {
		return generateListView(groups, null);
	}
}
